﻿using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using NFine.Code;
using NFine.Domain.Entity.ProductManage;
using NFine.Domain.Entity.SystemManage;
using NFine.Domain.IRepository.ProductManage;
using NFine.Domain.IRepository.SystemManage;
using NFine.Repository.ProductManage;
using NFine.Repository.SystemManage;

namespace NFine.Application.ProductManage
{
    public class ProductApp
    {
        private IProductRepository service = new ProductRepository();
        private IProductImageRepository imgService = new ProductImageRepository();
        //private IProductCategoryRepository cateService = new ProductCategoryRepository();
        //private ProductAttributeApp attrService = new ProductAttributeApp();
        //private ProductSkuApp productSkuApp = new ProductSkuApp();
        //private ProductSkuItemsApp productSkuItemsApp = new ProductSkuItemsApp();
        //private IProductType tservice = new ProductType();
        //private IBrandRepository bservice = new BrandRepository();
        //private ICategoryRepository categoryService = new CategoryRepository();
        //private AttributeApp attApp = new AttributeApp();
        //private CategoryApp categoryApp = new CategoryApp();
        //private IAttributeValueRepository valueService = new AttributeValueRepository();
        //private IAttribute attrbuteService = new NFine.Repository.ProductManage.Attribute();
        /// <summary>
        /// 获取商品列表 管理员查看所有商品 商家查看自己的
        /// </summary>
        /// <param name="pagination"></param>
        /// <param name="keyword"></param>
        /// <returns></returns>
        public List<ProductEntity> GetList(Pagination pagination, string keyword="",bool isAdmin=true)
        {
            var expression = ExtLinq.True<ProductEntity>();
            if (!isAdmin)
            {
                expression = expression.And(t => t.F_EnabledMark == true);
            }
            if (!string.IsNullOrEmpty(keyword))
            {
                expression = expression.And(t => t.F_ProductName.Contains(keyword));
                expression = expression.Or(t => t.F_ProductCode.Contains(keyword));
            }
           
            return service.FindList(expression, pagination).OrderBy(a => a.F_SortCode).ToList();
        }

        public List<ProductEntity> GetList()
        {
            return service.IQueryable(t => t.F_EnabledMark == true).OrderBy(a=>a.F_SortCode).ThenByDescending(a=>a.F_CreatorTime).ToList();
        }


        /// <summary>
        /// 获取单个商品
        /// </summary>
        /// <param name="keyValue"></param>
        /// <returns></returns>
        public ProductEntity GetForm(string keyValue)
        {
            return service.FindEntity(keyValue);
        }
        /// <summary>
        /// 保存商品信息
        /// </summary>
        /// <param name="pEntity"></param>
        /// <param name="keyValue"></param>
        /// <param name="list">商品属性信息</param>
        public int SubmitForm(ProductEntity pEntity, string keyValue,  string newPath)
        {
         
            return service.SubmitForm(pEntity, keyValue,  newPath);

        }
      /*  /// <summary>
        /// 保存产品规格
        /// </summary>
        /// <param name="selectedSku"></param>
        /// <returns></returns>
        private void saveProductItemsJson(out List<ProductSkuEntity> skuList, string selectedSku)
        {
            string img="";
            skuList = new List<ProductSkuEntity>();
            JArray skujArray = JArray.Parse(selectedSku);
            foreach (var productSku in skujArray)
            {
                ProductSkuEntity productSkuEntity = new ProductSkuEntity();
                productSkuEntity.F_CostPrice = Decimal.Parse(((JObject)productSku)["F_CostPrice"].ToString());
                productSkuEntity.F_SalePrice = Decimal.Parse(((JObject)productSku)["F_SalePrice"].ToString());
                productSkuEntity.F_EnabledMark = Convert.ToBoolean(((JObject)productSku)["F_EnabledMark"].ToString());
                productSkuEntity.F_Sku = ((JObject)productSku)["F_Sku"].ToString();
                productSkuEntity.F_Stock = int.Parse(((JObject)productSku)["F_Stock"].ToString());
                productSkuEntity.F_Weight = int.Parse(((JObject)productSku)["F_Weight"].ToString());
                JArray skuItemsjArray = JArray.Parse(((JObject)productSku)["SKUItems"].ToString());

                productSkuEntity.listSkuItems = new List<ProductSkuItemsEntity>();

                foreach (var productSkuItems in skuItemsjArray)
                {
                        ProductSkuItemsEntity productSkuItemsEntity = new ProductSkuItemsEntity();
                        productSkuItemsEntity.F_AttributeId = ((JObject)productSkuItems)["F_AttributeId"].ToString();
                        productSkuItemsEntity.F_ValueID = ((JObject)productSkuItems)["F_ValueID"].ToString();
                        productSkuItemsEntity.F_ValueStr = ((JObject)productSkuItems)["F_ValueStr"].ToString();
                    img=((JObject)productSkuItems)["F_ImageUrl"].ToString();
                    productSkuItemsEntity.F_ImageUrl =img== "undefined"?"":img;

                    productSkuEntity.listSkuItems.Add(productSkuItemsEntity);
                    }
                skuList.Add(productSkuEntity);
            }
        }*/
        /// <summary>
        /// 查看商品详情
        /// </summary>
        /// <param name="keyValue"></param>
        /// <returns></returns>
        public ProductEntity GetFormForView(string keyValue)
        {
            var product = service.FindEntity(a => a.F_Id == keyValue);

           /* if (!string.IsNullOrEmpty(product.F_TypeId))
            {
                //获取商品类型属性及值  商品属性值
                product.ProductattrList = attApp.GetListByTypeId(product.F_TypeId, 0);
                product.attrList = attrService.GetListByParentId(keyValue);

                //类别
                ProductTypeEntity t = tservice.FindEntity(a => a.F_Id == product.F_TypeId);
                product.TypeName = t != null ? t.F_TypeName : "";
            }
            if (!string.IsNullOrEmpty(product.F_BrandId))//品牌
            {
                BrandEntity b = bservice.FindEntity(a => a.F_Id == product.F_BrandId);
                product.F_BrandId = b != null ? b.F_BrandName : "";
            }*/
            return product;
        }
        /// <summary>
        /// 删除商品
        /// </summary>
        /// <param name="keyValues">商品id ，分割</param>
        public int DeleteProducts(string keyValues)
        {
            return service.DeleteProducts(keyValues);
        }
        /// <summary>
        /// 根据商品id获取图片url
        /// </summary>
        /// <param name="keyValues">商品id ，分割</param>
        /// <returns></returns>
        public string[] GetImagesByProductID(string keyValues)
        {
            string[] otherImage = imgService.IQueryable(a => keyValues.Contains(a.F_ProductId)).Select(a => a.F_ImageUrl).ToArray();
            return service.IQueryable(a => keyValues.Contains(a.F_Id)).Select(a => a.F_ImageUrl).ToArray().Union(otherImage).ToArray();
        }
        /// <summary>
        /// 上架/下架商品
        /// </summary>
        /// <param name="ids"></param>
        /// <param name="flag"></param>
        /// <returns></returns>
        public int inStock(string ids, int flag)
        {
            return service.inStock(ids, flag);
        }
        /// <summary>
        /// 审核商品
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public int auditProducts(string ids)
        {
            return service.auditProducts(ids);
        }
      /*  /// <summary>
        /// 获取商品属性信息
        /// </summary>
        /// <param name="keyValue"></param>
        /// <returns></returns>
        public List<ProductAttributeEntity> GetProductAttrById(string keyValue)
        {
            List<AttributeEntity> list_Attr = null;
            List<AttributeValueEntity> list_Value = null;
            #region 获取商品属性信息
            //获取商品属性信息 
            List<ProductAttributeEntity> List_productAttr = attrService.GetListByParentId(keyValue);

            //重新定义该商品属性集合（多选的合并）
            List<ProductAttributeEntity> List_ProductAttr = new List<ProductAttributeEntity>();
            if (List_productAttr != null && List_productAttr.Count() > 0)
            {

                //该商品所有属性信息
                string[] Attrs = List_productAttr.Select(a => a.F_AttributeId).ToArray();
                list_Attr = attrbuteService.IQueryable(a => Attrs.Contains(a.F_Id)).ToList();
                //该商品所有属性值信息
                string[] values = List_productAttr.Select(a => a.F_ValueId).ToArray();
                list_Value = valueService.IQueryable(a => values.Contains(a.F_Id)).ToList();
                ProductAttributeEntity attrModel = null;
                AttributeEntity attrEntity = null;
                foreach (var a in List_productAttr)
                {
                    attrModel = List_ProductAttr.SingleOrDefault(t => t.F_AttributeId == a.F_AttributeId);
                    if (attrModel != null)//多选  （多条记录）
                    {
                        if (list_Value.Any(v => v.F_Id == a.F_ValueId))
                        {
                            attrModel.ValueName += "," + list_Value.SingleOrDefault(v => v.F_Id == a.F_ValueId).F_ValueStr;//属性值名称;
                        }
                    }
                    else
                    {
                        attrEntity = list_Attr.SingleOrDefault(t => t.F_Id == a.F_AttributeId);
                        if (attrEntity != null)
                        {
                            if (attrEntity.F_UsageMode != 3)//属性
                            {
                                //对应的属性值
                                AttributeValueEntity curAttrValue = list_Value.SingleOrDefault(v => v.F_Id == a.F_ValueId);
                                a.AttributeName = attrEntity.F_AttributeName;//属性名
                                if (attrEntity.F_UsageMode != 2)
                                {
                                    a.ValueName = curAttrValue != null ? curAttrValue.F_ValueStr : "";//属性值名称
                                }
                                else
                                {
                                    a.ValueName = a.F_ValueId;
                                }

                                List_ProductAttr.Add(a);
                            }
                        }
                    }
                }
            }
          return   List_ProductAttr;
            #endregion
        }*/
    }
}
